import path from "node:path";
import fs from "fs-extra";

export default function renderTemplate(templateDir: string, dest: string) {
  const files = fs.readdirSync(templateDir);
  for (const file of files) {
    const src = path.join(templateDir, file);
    const destPath = path.join(dest, file);
    const stats = fs.statSync(src);

    if (stats.isDirectory()) {
      if (path.basename(src) === "node_modules") continue;
      fs.ensureDirSync(destPath);
      renderTemplate(src, destPath);
      continue;
    }

    const filename = path.basename(src);

    // 处理需要合并的 JSON 文件
    if (
      ["package.json", "tsconfig.json"].includes(filename) &&
      fs.existsSync(destPath)
    ) {
      const existing = fs.readJsonSync(destPath);
      const newData = fs.readJsonSync(src);
      fs.writeJsonSync(destPath, { ...existing, ...newData }, { spaces: 2 });
      continue;
    }

    // 处理特殊文件重命名
    if (filename.startsWith("_")) {
      const newDest = path.join(
        path.dirname(destPath),
        filename.replace(/^_/, ".")
      );
      fs.copySync(src, newDest);
      continue;
    }

    // 普通文件拷贝
    fs.copySync(src, destPath);
  }
}
